package jmine.tec.utils.collection;

import java.util.Enumeration;
import java.util.Set;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

/**
 * @author jrenaut
 */
public class ASortedPropertiesShould {

    private SortedProperties p;

    @Before
    public void before() {
        this.p = new SortedProperties();
        this.p.put("a", "a");
        this.p.put("d", "d");
        this.p.put("c", "c");
        this.p.put("b", "b");
        this.p.put("e", "e");
    }

    @Test
    public void haveSortedKeys() {
        String previous = null;
        Enumeration<Object> keys = this.p.keys();
        while (keys.hasMoreElements()) {
            String current = keys.nextElement().toString();
            if (previous != null) {
                Assert.assertTrue(previous.compareTo(current) <= 0);
            }
            previous = current;
        }
    }

    @Test
    public void haveASortedKeyset() {
        this.assertKeySetIsSorted();
    }

    private void assertKeySetIsSorted() {
        String previous = null;
        Set<Object> keys = this.p.keySet();
        for (Object key : keys) {
            String current = key.toString();
            if (previous != null) {
                Assert.assertTrue(previous.compareTo(current) <= 0);
            }
            previous = current;
        }
    }

    @Test
    public void clear() {
        Assert.assertTrue(this.p.keys().hasMoreElements());
        Assert.assertFalse(this.p.keySet().isEmpty());
        this.p.clear();
        Assert.assertFalse(this.p.keys().hasMoreElements());
        Assert.assertTrue(this.p.keySet().isEmpty());
    }

    @Test
    public void remainSortedAfterPut() {
        this.assertKeySetIsSorted();
        Assert.assertFalse(this.p.containsKey("f"));
        this.p.put("f", "f");
        Assert.assertTrue(this.p.keySet().contains("f"));
        this.assertKeySetIsSorted();
    }

    @Test
    public void remainSortedAfterRemove() {
        this.assertKeySetIsSorted();
        Assert.assertTrue(this.p.containsKey("d"));
        this.p.remove("d");
        Assert.assertFalse(this.p.keySet().contains("d"));
        this.assertKeySetIsSorted();
    }

}
